package org.shj.algorithm;

/**
 * @author Shen Huang Jian
 * @date 2021-02-05 8:59
 */
public class TargetSum {

    public static void main(String[] args){
//        int[] nums = {40, 40, 23, 30, 29, 12, 2, 15, 3, 0};
//        int s = 28;
        int[] nums = {2, 1, 1, 2};
        int s = 3;
        System.out.println(findTargetSumWays(nums, s));
    }

    public static int findTargetSumWays(int[] nums, int s) {
        int maxSum = 6;
        int[][] dp = new int[nums.length][2*maxSum + 1];
        dp[0][nums[0] + maxSum] = 1;
        dp[0][-nums[0] + maxSum] += 1;
        for (int i = 1; i < nums.length; i++) {
            for (int sum = -maxSum; sum <= maxSum; sum++) {
                if (dp[i - 1][sum + maxSum] > 0) {
                    dp[i][sum + nums[i] + maxSum] += dp[i - 1][sum + maxSum];
                    dp[i][sum - nums[i] + maxSum] += dp[i - 1][sum + maxSum];
                }
            }
        }
        return s > maxSum ? 0 : dp[nums.length - 1][s + maxSum];
    }
}
